package com.hurt.competition.common.data;

import com.hurt.competition.admin.dto.EmailCodeData;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Date: 2023/05/11 11:33 下午
 * @Description：这里可以用Redis代替
 */
public class ResetPwdCodeData {

    /**
     * key 为邮箱，value为发送的验证码
     */
    private static Map<String, List<EmailCodeData>> codeMap = new ConcurrentHashMap<>(16);

    /**
     * 过期时间  单位：分钟
     */
    private static Integer expireTime = 5;

    public static void clear(){
        codeMap.clear();
    }

    public static List<EmailCodeData> get(String email){
        return codeMap.get(email);
    }

    public static Boolean valid(String email,Integer code){
        List<EmailCodeData> emailCodeData = codeMap.get(email);
        if(CollectionUtils.isEmpty(emailCodeData)){
            return false;
        }

        Iterator<EmailCodeData> iterator = emailCodeData.iterator();
        while (iterator.hasNext()){
            EmailCodeData data = iterator.next();
            if(data.getExpireDate().compareTo(new Date())<0){
                // 该验证码过期了
                iterator.remove();
                continue;
            }

            if(data.getCode().equals(code)){
                iterator.remove();
                return true;
            }
        }

        return false;
    }

    public static void put(String email,Integer code){
        List<EmailCodeData> codeDataList = codeMap.get(email);
        if(codeDataList==null){
            codeDataList = new ArrayList<>();
            codeMap.put(email,codeDataList);
        }
        EmailCodeData codeData = new EmailCodeData();
        codeData.setCode(code);
        codeData.setExpireDate(DateUtils.addMinutes(new Date(),expireTime));
        codeDataList.add(codeData);
    }
}
